#include "softwareuninstallation.h"
#include "ui_softwareuninstallation.h"
#include "AuditPlanFun.h"
#include <QClipboard>
#include "curl.h"
#include <string>
#include <QFile>
#include <QMessageBox>
#include <QProcess>
#include <QDir>
#include <windows.h>
#include <QFileInfo>

SoftwareUninstallation::SoftwareUninstallation(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SoftwareUninstallation)
{
    ui->setupUi(this);
    //标题修改

    setWindowTitle("审计移动存储安全平台");
    setWindowIcon(QIcon(":/icons/images/Upan2.png"));

    ui->groupBox_2->setStyleSheet("QGroupBox { background-color: white; "
                                  "border: none; "
                                  "margin-top: 1.5ex; }");
    QPixmap pixmap(":/icons/images/logo.png");

    ui->label->setText("技术支持单位: \n西安电子科技大学青岛计算技术研究院");
    ui->label->setAlignment(Qt::AlignCenter);

    ui->lineEdit_MacCode->setStyleSheet("QLineEdit { border: 1px solid #CCCCCC; background-color: #ADD8E6; border-radius: 5px;  }"
                                                 "QLineEdit:focus { border: 1px solid green; }"
                                                 "QLineEdit:hover { border: 1px solid green; }"
                                                 "QLineEdit:pressed { border: 1px solid green; }");
    UsbEncrypt::AuditFun a;
    QString str = QString::fromStdString(a.getMac());
    str.replace(":", "-");
    ui->lineEdit_MacCode->setText(" Mac地址："+str);

    ui->lineEdit_VerificationCode->setStyleSheet("QLineEdit { border: 1px solid #CCCCCC; background-color: transparent; border-radius: 5px;  }"
                                                 "QLineEdit:focus { border: 1px solid green; }"
                                                 "QLineEdit:hover { border: 1px solid green; }"
                                                 "QLineEdit:pressed { border: 1px solid green; }");

    ui->lineEdit_VerificationCode->addAction(ui->actionVerCode, QLineEdit::TrailingPosition);


    QString buttonStyle = "QPushButton { background-color: #ADD8E6; border-radius: 6px; }"
                          "QPushButton:pressed { background-color: #6FAAD8; }";
    // 应用样式表
    ui->btnCopyMac->setStyleSheet(buttonStyle);
    ui->btnUninstall->setStyleSheet(buttonStyle);
    int heigth = ui->btnCopyMac->height()+3;
    ui->lineEdit_MacCode->setFixedHeight(heigth);
    ui->lineEdit_VerificationCode->setFixedHeight(heigth);
}

SoftwareUninstallation::~SoftwareUninstallation()
{
    delete ui;
}

void SoftwareUninstallation::on_btnCopyMac_clicked()
{
    QString str = ui->lineEdit_MacCode->text();
    int index = str.indexOf("：");
    QString result = str.mid(index + 1).trimmed();
    QClipboard *clipboard = QGuiApplication::clipboard();
    clipboard->setText(result);
}


void SoftwareUninstallation::on_actionVerCode_triggered()
{
    if (ui->lineEdit_VerificationCode->echoMode() == QLineEdit::Password) {
        // 如果当前为密码格式，则设置为普通可见模式
        QIcon icon(":/icons/images/passwdHover.png");
        // 改变图标大小
        icon = icon.pixmap(QSize(30, 30)); // 这里指定了新的图标尺寸
        ui->actionVerCode->setIcon(icon);
        ui->lineEdit_VerificationCode->setEchoMode(QLineEdit::Normal);
    } else {
        // 否则设置为密码格式
        ui->actionVerCode->setIcon(QIcon(":/icons/images/passwd.png"));
        ui->lineEdit_VerificationCode->setEchoMode(QLineEdit::Password);
    }
}


size_t getData(void *ptr, size_t size, size_t nmemb, void *userdata) {
    std::string *str = static_cast<std::string*>(userdata);
    size_t totalSize = size * nmemb;
    str->append(static_cast<char*>(ptr), totalSize);
    return totalSize;
}

void SoftwareUninstallation::on_btnUninstall_clicked()
{
    CURL *curl = nullptr;
    CURLcode res;
    std::string response="";
    curl = curl_easy_init();

    QString ip = "127.0.0.1";
    QFile file("ip.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "无法打开文件";
    }
    QTextStream in(&file);
    while (!in.atEnd())
    {
        ip = in.readLine();  // 逐行读取数据
        qDebug() << ip;
    }
    file.close();

    QString ipaddress = ip;

    QString str = ui->lineEdit_MacCode->text();
    int index = str.indexOf("：");
    QString Mac = str.mid(index + 1).trimmed();
    Mac.toStdString().c_str();
    QString Code = ui->lineEdit_VerificationCode->text();
    Code.toStdString().c_str();

    QString url = "http://" + ipaddress + "/common/verifyUnloadCode?mac=" + Mac + "&code=" + Code;
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);  // 使用 GET 请求
        curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); // 指定url

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
        {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        }

        curl_easy_cleanup(curl);
    }

    std::string code = response.substr(response.length()-4, 3);
    std::cout <<"code:" <<code << std::endl;
    if(code == "200"){
        ui->label_state->setText("当前卸载授权状态：已授权");
        qDebug()<<"当前卸载授权状态：已授权";

        QString exeFilePath = QCoreApplication::applicationFilePath();
        QFileInfo fileInfo(exeFilePath);
        QString destPath = fileInfo.absolutePath().replace("/", "\\") + "\\uninstall.bat";
        //QMessageBox::information(nullptr, "当前路径", destPath);
        QMessageBox::StandardButton reply;
        reply = QMessageBox::warning(this, "警告", "危险操作！请确认是否要卸载软件。",
                                     QMessageBox::Yes | QMessageBox::No);

        if (reply == QMessageBox::Yes) {
            QProcess process;
            QString program = "taskkill";

            QStringList arguments1;
            arguments1 << "/F" << "/IM" << "app.exe";
            process.start(program, arguments1);
            process.waitForFinished();

            // 将 QString 转换为 LPCWSTR 类型的 C 字符串
            LPCWSTR program1 = reinterpret_cast<LPCWSTR>(destPath.utf16());
            // 使用 ShellExecute 启动 .bat 文件，并请求管理员权限
            HINSTANCE hInstance = ShellExecute(NULL, L"runas", program1, NULL, NULL, SW_SHOWNORMAL);
            // 检查启动结果
            if (reinterpret_cast<intptr_t>(hInstance) <= 32) {
                //QMessageBox::information(nullptr, "申请失败", "Error: Failed to start uninstall");
                qDebug() << "Error: Failed to start uninstall";
            } else {
                qDebug() << "Started uninstall with elevated privileges";
            }


            QStringList arguments2;
            arguments2 << "/F" << "/IM" << "Upan2.exe";
            process.start(program, arguments2);
            process.waitForFinished();

            qDebug() << "用户点击了确认键";
            //QMessageBox::information(nullptr, "用户点击了确认键", destPath);
        } else if (reply == QMessageBox::No) {
            ui->lineEdit_VerificationCode->clear();
            ui->label_state->setText("当前卸载授权状态：未授权");
            qDebug() << "用户点击了取消键";
            //QMessageBox::information(nullptr, "用户点击了取消键", destPath);
        }
    }
    else{
        ui->label_state->setText("当前卸载授权状态：未授权");
        QMessageBox::information(nullptr, "申请失败", "Mac地址或卸载码错误！");
    }

}

